<template>
  <div>
    <!-- 三级分类全局组件 -->
    <Category :scene="scene" />
    <el-card style="margin: 10px 0px">
      <div v-show="scene == 0">
        <el-button
          @click="addAttr"
          type="primary"
          size="default"
          icon="Plus"
          :disabled="categoryStore.c3Id ? false : true"
          >添加属性</el-button
        >
        <el-table border style="margin: 10px 0px" :data="attrArr">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="120px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-tag
                style="margin: 5px"
                v-for="(item, index) in row.attrValueList"
                :key="item.id"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <!-- row：已有的属性对象 -->
            <template #="{ row, $index }">
              <!-- 修改已有属性的按钮 -->
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="updateAttr(row)"
              ></el-button>
              <el-popconfirm
                :title="`你确定删除${row.attrName}?`"
                width="200px"
                @confirm="deleteAttr(row.id)"
              >
                <template #reference>
                  <el-button
                    type="primary"
                    size="small"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <!-- 展示添加属性与修改数据的结构 -->
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              placeholder="请你输入属性名称"
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          @click="addAttrValue"
          :disabled="attrParams.attrName ? false : true"
          type="primary"
          size="default"
          icon="Plus"
          >添加属性值</el-button
        >
        <el-button type="primary" size="default" @click="cancel"
          >取消</el-button
        >
        <el-table
          border
          style="margin: 10px 0px"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            label="序号"
            width="80px"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <!-- row:即为当前属性值对象 -->
            <template #="{ row, $index }">
              <el-input
                :ref="(vc: any) => inputArr[$index] = vc"
                v-if="row.flag"
                size="small"
                placeholder="请你输入属性值名称"
                v-model="row.valueName"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作">
            <template #="{ row, index }">
              <el-button
                type="primary"
                size="small"
                icon="Delete"
                @click="attrParams.attrValueList.splice(index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          @click="save"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
          >保存</el-button
        >
        <el-button type="primary" size="default" @click="cancel"
          >取消</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
//组合式API函数watch
import { watch, ref, reactive, nextTick, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from "@/api/attr";
import useCategoryStore from "@/store/modules/category";
import { AttrResponseData, Arrt, Arrt2 } from "@/api/attr/type";
const categoryStore = useCategoryStore();
// 列表数组
const attrArr = ref<Arrt[]>([]);
//获取已有的属性与属性值方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore;
  //获取分类下的已有的属性与属性值
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id);
  if (result.code == 200) {
    attrArr.value = result.data;
  }
};
// 监听第三级被选中
watch(
  () => categoryStore.c3Id,
  async (neV, olV) => {
    console.log(categoryStore.c3Id, neV, olV);

    attrArr.value = [];
    if (!categoryStore.c3Id) return;
    //获取分类的ID
    getAttr();
  },
  { immediate: true }
);

const scene = ref<number>(0);
//收集新增的属性的数据
let attrParams = reactive<any>({
  attrName: "", //新增的属性的名字
  attrValueList: [
    //新增的属性值数组
  ],
  categoryId: "", //三级分类的ID
  categoryLevel: 3, //代表的是三级分类
});
//准备一个数组:将来存储对应的组件实例el-input
let inputArr = ref<any>([]);
// 添加属性
const addAttr = () => {
  //每一次点击的时候,先清空一下数据再收集数据
  Object.assign(attrParams, {
    attrName: "", //新增的属性的名字
    attrValueList: [
      //新增的属性值数组
    ],
    categoryId: categoryStore.c3Id, //三级分类的ID
    categoryLevel: 3, //代表的是三级分类
  });
  //切换为添加与修改属性的结构
  scene.value = 1;
};

// 修改
const updateAttr = (row: Arrt) => {
  scene.value = 1;
  Object.assign(attrParams, row);
};
// 删除
const deleteAttr = async (attrId: number) => {
  const result: any = await reqRemoveAttr(attrId);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getAttr();
  } else {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
};
// 添加属性值
const addAttrValue = () => {
  if (!attrParams.attrValueList.length || isEvery()) {
    attrParams.attrValueList.push({
      valueName: "",
      flag: true,
    });
    // 聚焦新添加的input参数
    nextTick(() => {
      inputArr.value[attrParams.attrValueList.length - 1].focus();
    });
  } else {
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
  }
};
const isEvery = () => {
  return attrParams.attrValueList.every((item: any) => item.valueName);
};
// 取消添加属性值
const cancel = () => {
  scene.value = 0;
};
// 保存
const save = async () => {
  const result: any = await reqAddOrUpdateAttr(attrParams);
  if (result.code == 200) {
    //切换场景
    scene.value = 0;
    //提示信息
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功",
    });
    //获取全部已有的属性与属性值
    getAttr();
  } else {
    ElMessage({
      type: "error",
      message: attrParams.id ? "修改失败" : "添加失败",
    });
  }
};
// 编辑
const toEdit = (row: Arrt2, index: number) => {
  row.flag = true;
  //nextTick:响应式数据发生变化,获取更新的DOM(组件实例)
  nextTick(() => {
    inputArr.value[index].focus();
  });
};
</script>

<style scoped></style>
